# _*_ coding: utf-8 _*_
from odoo import models, fields, api, _
from odoo.exceptions import Warning
import odoo.addons.decimal_precision as dp


class OLPurchaseRequisitionLineExtend(models.Model):
    _inherit = ["purchase.requisition.line", "stock.view.quant.mixin"]
    _name = "purchase.requisition.line"
    _order = "sequence"

    product_purchase_limit_control = fields.Boolean(string="Template Purchase Limit Control",
                                                    related="product_id.product_purchase_limit_control", readonly=True)
    product_purchase_limit = fields.Float(string="Template Limit",
                                          related="product_id.product_purchase_limit", readonly=True)
    department_id = fields.Many2one("hr.department", string="Department",
                                    related="product_id.categ_id.department_id",
                                    readonly=True, store=True)
    user_id = fields.Many2one("res.users", string="Purchase User", readonly=True, related='user_id_onchange', store='True')
    user_id_onchange = fields.Many2one("res.users", string=u'采购员')
    requisition_user_id = fields.Many2one("res.users", string=u'请购人员', related='requisition_id.user_id', readonly=True)
    requisition_department = fields.Many2one("hr.department", string=u"使用部门", related='requisition_id.department_id', readonly=True)
    state = fields.Selection([
        ("draft", "Draft"),
        ("confirm", "Confirm"),
        ("assign", "Assign"),
        ("pricing", "Pricing"),
        ("done", "Done"),
        ("cancel", "Cancel"),
    ], default="draft")
    requisition_state = fields.Selection(related='requisition_id.state', string='State', readonly=True)
    memo = fields.Text('Memo')
    sequence = fields.Integer(string="Sequence", related='requisition_id.sequence', readonly=True, store=True)
    emergent = fields.Boolean(string="Emergent", related='requisition_id.emergent', readonly=True, store=True)
    maximum_stock_qty = fields.Float('Maximum Stock Quantity', related='product_id.maximum_stock_qty', digits=dp.get_precision('Product Unit of Measure'), readonly=True)
    readonly_uom_id = fields.Many2one('product.uom', string='Product Unit of Measure', store=True)
    last_create_date = fields.Date('Last Create Date',compute='_last_data')
    current_create_date = fields.Date('Current Create Date',compute='_last_data')
    last_product_qty = fields.Float(string='Last Quantity', digits=dp.get_precision('Product Unit of Measure'))
    current_product_qty = fields.Float(string='Current Quantity', digits=dp.get_precision('Product Unit of Measure'))
    # product_qty = fields.Float(default=1)

    def action_confirm(self):
        self.write({
            "state": "confirm"
        })

    def action_cancel(self):
        self.write({
            "state": "cancel"
        })

    @api.multi
    def action_view_quants_by_item(self):
        return self.action_view_quant_by_product_ids([self.product_id.id])

    @api.multi
    def unassign_purchase_request(self):
        for line in self:
            if line.state != 'assign':
                raise Warning(_("The target state must be assign."))
            line.write({
                "user_id": False,
                "state": "confirm"
            })

    @api.onchange('product_id')
    def _onchange_product_id(self):
        for line in self:
            line.user_id = line.product_id.categ_id.user_id
            line.user_id_onchange = line.product_id.categ_id.user_id
            line.readonly_uom_id = line.product_id.uom_id
            line.product_uom_id = line.product_id.uom_id

    @api.onchange('product_qty')
    def _onchange_product_qty_for_check(self):
        # REQ 320
        if self.product_id and self.check_maximum_stock_qty():
            warning = {
                'title': _('Warning!'),
                'message': _('Product qty will out of the maximum stock qty, please check available on hand.'),
            }
            return {'warning': warning}

    @api.model
    def check_maximum_stock_qty(self):
        self.ensure_one()
        product_required = {}
        # sum all line's qty
        for line in self.requisition_id.line_ids:
            if line.product_id in product_required:
                product_required[line.product_id.id] += line.product_qty
            else:
                product_required[line.product_id.id] = line.product_qty
        # check product_qty + onhand must lt than maximum qty
        product = self.env['product.product']
        for product_id, product_qty in product_required.iteritems():
            pp = product.browse(product_id)
            if pp.qty_available + product_qty > pp.maximum_stock_qty:
                return True
        return False

    @api.depends('product_id')
    def _last_data(self):
        for record in self:
            line_ids = []
            if record.product_id:
                requisition_lines = self.env['purchase.requisition.line'].sudo().search(
                    [('product_id', '=', record.product_id.id),
                     ('requisition_state', 'in', ('done', 'open'))])
                if requisition_lines:
                    for lines in requisition_lines:
                        line_ids.append(lines.id)
            final_list = sorted(line_ids, key=int, reverse=True)
            if len(final_list) >= 1:
                last_data = self.env['purchase.requisition.line'].sudo().browse(final_list[0])
                record.last_create_date = last_data.create_date
                record.last_product_qty = last_data.product_qty